package com.coder.algorithm.offer_2;

/**
 * 顺时针打印矩阵
 *
 * @author yuhushuan
 * @date 2020/6/20 11:55
 */
public class _29_1_PrintMatrix {
    private static void printMatrix(int[][] matrix) {
        if (matrix == null) {
            System.out.println("null");
        } else {
            printMatrix(matrix, 0, matrix.length - 1, 0, matrix[0].length - 1);
        }
    }

    private static void printMatrix(int[][] matrix, int rowStart, int rowEnd, int colStart, int colEnd) {
        if (matrix == null || rowStart > rowEnd || colStart > colEnd) {
            return;
        }
        // rowStart
        for (int col = colStart; col <= colEnd; ++col) {
            print(matrix[rowStart][col]);
        }
        rowStart++;
        // colEnd
        if (colStart <= colEnd) {
            for (int row = rowStart; row <= rowEnd; ++row) {
                print(matrix[row][colEnd]);
            }
        }
        colEnd--;

        // rowEnd
        if (rowStart <= rowEnd) {
            for (int col = colEnd; col >= colStart; --col) {
                print(matrix[rowEnd][col]);
            }
        }
        rowEnd--;
        // colStart
        if (colStart <= colEnd) {
            for (int row = rowEnd; row >= rowStart; --row) {
                print(matrix[row][colStart]);
            }
        }
        colStart++;
        printMatrix(matrix, rowStart, rowEnd, colStart, colEnd);
    }

    private static void print(int number) {
        System.out.print(number + " ");
    }

    public static void main(String[] args) {
        int[][] matrix;
        // 数组中有多行多列
        matrix = new int[][]{
                {1, 2, 3, 4},
                {5, 6, 7, 8},
                {9, 10, 11, 12},
                {13, 14, 15, 16}
        };
        printTest(matrix);

        matrix = new int[][]{
                {1, 2, 3, 4, 5},
                {6, 7, 8, 9, 10},
                {11, 12, 13, 14, 15},
                {16, 17, 18, 19, 20},
                {21, 22, 23, 24, 25}
        };
        printTest(matrix);

        // 数组中只有一行
        matrix = new int[][]{
                {1, 2, 3, 4}
        };
        printTest(matrix);

        // 数组中只有一列
        matrix = new int[][]{
                {1},
                {5},
                {9},
                {13}
        };
        printTest(matrix);

        // 数组中只有一行一列
        matrix = new int[][]{
                {1}
        };
        printTest(matrix);
    }

    static void printTest(int[][] matrix) {
        System.out.println("矩阵：");
        if (matrix == null) {
            System.out.println("null");
        } else {
            for (int row = 0; row < matrix.length; ++row) {
                for (int col = 0; col < matrix[0].length; ++col) {
                    print(matrix[row][col]);
                }
                System.out.println();
            }
        }
        System.out.println("顺时间打印为：");
        printMatrix(matrix);
        System.out.println("\n");
    }

}
